import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_jd/widget/jdButton.dart';
import '../../services/ScreenAdatper.dart';
import '../../model/ProdicContentModel.dart';
import '../../config/config.dart';
import '../../services/EventBus.dart';
import './CartNum.dart';
import '../../services/CartServices.dart';
import 'package:provider/provider.dart';
import '../../provider/Cart.dart';

class ProductContentFirst extends StatefulWidget {
  final List _productContentList;

  ProductContentFirst(this._productContentList, {Key key}) : super(key: key);

  _ProductContentFirstState createState() => _ProductContentFirstState();
}

class _ProductContentFirstState extends State<ProductContentFirst> with AutomaticKeepAliveClientMixin{
  bool get wantKeepAlive => true; //with AutomaticKeepAliveClientMixin  继承缓存之后要调用才生效   父组件要用  TabBarView  PageView  包裹才可用  AutomaticKeepAliveClientMixin
  ProdicContentItem _productContent;
  List _attr = [];
  String _attrValue;
  var actionEventBus;  
  var _cartProvider;
  @override
  void initState() {
    super.initState();
    this._productContent = widget._productContentList[0];
    this._attr = this._productContent.attr;
    _initAttr();
    // 必须要页面销毁时取消监听 eventBus
    this.actionEventBus = eventBus.on<ProductContentEvent>().listen((event){  //eventBus.on().listen((event){});  // 监听所有广播
      print(event);
      this._attrBottomSheet();
    });
  }
  @override
  void dispose() { 
    super.dispose();
    //取消监听eventBus
    this.actionEventBus.cancel();
  }
  //初始化attr 格式化数据
  _initAttr(){
    List attr = this._attr;
    // List attrs = [];
    List attrs = attr.map((v){
      var i = 0;
      var list = v.list.map((t){
        var json = {
          "title":t,
          "checked": i == 0
        };
        i++;
        return json;
       
      }).toList(); 
      return {
        'cate':v.cate,
        'list':list
      };
    }).toList();
    print(attrs);
    setState(() {
      this._attr = attrs;
      _getSelectdAttrValue();
    });
  }
  // 获取选中的值
  _getSelectdAttrValue(){ 
    List value = []; 
    this._attr.forEach((e){
      e['list'].forEach((l){
        if(l['checked']){
          value.add("${l['title']}");
        }
      });
    });
    print(value);
    setState(() {
      this._attrValue = value.join(',');
      this._productContent.selectAttr = this._attrValue;
    });
  }
  // 改变属性
  _changeAttr(cate,title,setBottomState){
     List arrts = this._attr;
     arrts = arrts.map((e){
       if(e['cate'] == cate){
         e['list'] = e['list'].map((l){
           l['checked'] = l['title'] == title;
           return l;
         }).toList(); 
       }
       return e;
     }).toList();
     setBottomState(() {  //想要改变showModalBottomSheet 里面的值 就要使用 StatefulBuilder 里面的 setBottomState 来改变
       this._attr = arrts;
       _getSelectdAttrValue();
     });
  }
  List<Widget> _arrrItem(attrList,setBottomState){
    List<Widget> item = [];
    attrList['list'].forEach((e){
      item.add(Container(
        margin: EdgeInsets.all(10),
        child: InkWell(
          onTap: (){
            _changeAttr(attrList['cate'],e['title'],setBottomState);
          },
          child: Chip(
            backgroundColor: e['checked'] ? Colors.red : Colors.black26,
            label: Text("${e['title']}",style: TextStyle(
              color: e['checked'] ? Colors.white : Colors.black
            ),),
            padding: EdgeInsets.all(10),
          ),
        ),
      ));
    });
    return item;
  }
  List<Widget> _arrrItemList(setBottomState){
    List<Widget> list = []; 
    this._attr.forEach((item) {
      list.add(Wrap(
        children: <Widget>[
          Container(
            width: ScreenAdatper.width(150),
            padding:EdgeInsets.only(top: ScreenAdatper.width(45)),
            child: Text(
              "${item['cate']}:",
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Container(
            width: ScreenAdatper.width(550),
            child: Wrap(
              children: _arrrItem(item,setBottomState),
            ),
          )
        ],
      ));
    });
    return list;
  }
  _attrBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (contex) {
          return StatefulBuilder(  //
            builder: (BuildContext context, setBottomState) {
              return GestureDetector(
                  //解决点击消失的问题
                  child: Container(
                    padding: EdgeInsets.all(ScreenAdatper.width(20)),
                    height: ScreenAdatper.height(700),
                    child: Stack( 
                      children: <Widget>[
                        ListView(
                          children:<Widget>[
                            Column(
                              children: _arrrItemList(setBottomState),

                            ),
                            Divider(),
                            Container(
                              height: ScreenAdatper.height(60),
                              child: InkWell(
                                child: Row(
                                  children: <Widget>[
                                    Text("数量：",style: TextStyle(fontWeight: FontWeight.bold)),
                                    Container(
                                      margin: EdgeInsets.only(left: ScreenAdatper.width(50)),
                                      child: CartNum(this._productContent),
                                    )
                                  ],
                                )
                              ),
                            )
                          ],  //如果遇到嵌套循环的话就要拆分出来
                        ), 
                        Positioned(
                          bottom: 0,
                          width: ScreenAdatper.width(750),
                          height: ScreenAdatper.height(76),
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                flex: 1,
                                child: Container(
                                    alignment: Alignment.center,
                                    child: JdButtoon(
                                      color: Colors.red,
                                      text: '加入购物车',
                                      onTap: () async {
                                        await CartServices.addCart(this._productContent);
                                        Navigator.of(context).pop();
                                        //调用Provider 更新下购物车列表
                                        this._cartProvider.updateCartList();
                                      },
                                    )),
                                    
                              ),
                              Expanded(
                                flex: 1,
                                child: Container(
                                    alignment: Alignment.center,
                                    child: JdButtoon(
                                      color: Colors.orange,
                                      text: '立即购买',
                                    )),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                    //解决点击消失的问题
                    return false;
                  },
                );
            },
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    this._cartProvider = Provider.of<Cart>(context);
    String sPic = Config.domain + this._productContent.pic.replaceAll('\\', '/');
    return Container(
      padding: EdgeInsets.all(ScreenAdatper.width(10)),
      child: ListView(
        children: <Widget>[
          AspectRatio(
            aspectRatio: 16 / 12,
            child: Image.network(
              sPic,
              fit: BoxFit.cover,
            ),
          ),
          Container(
            padding: EdgeInsets.all(ScreenAdatper.height(10)),
            child: Text(
              this._productContent.title,
              style: TextStyle(
                color: Colors.black87,
                fontSize: ScreenAdatper.size(36),
              ),
              overflow: TextOverflow.ellipsis,
              maxLines: 2,
            ),
          ),
          Container(
            padding: EdgeInsets.all(ScreenAdatper.height(10)),
            child: Text(
              "${this._productContent.subTitle}",
              style: TextStyle(
                color: Colors.black54,
                fontSize: ScreenAdatper.size(28),
              ),
              overflow: TextOverflow.ellipsis,
              maxLines: 2,
            ),
          ),
          Container(
            padding: EdgeInsets.all(ScreenAdatper.height(10)),
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Row(
                    children: <Widget>[
                      Text("特价"),
                      Text(
                        "￥${this._productContent.price}",
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: ScreenAdatper.size(36)),
                      )
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      Text("原价"),
                      Text(
                        "￥${this._productContent.oldPrice}",
                        style: TextStyle(
                            color: Colors.black38,
                            fontSize: ScreenAdatper.size(28),
                            decoration: TextDecoration.lineThrough),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
            // height: ScreenAdatper.height(80),
            padding: EdgeInsets.all(ScreenAdatper.height(10)),
            child: Column(
              children: <Widget>[
                this._attr.length > 0 ? Container(
                  height: ScreenAdatper.height(60),
                  child: InkWell(
                    child: Row(
                      children: <Widget>[
                        Text("已选",style: TextStyle(fontWeight: FontWeight.bold)),
                        Container(
                          margin: EdgeInsets.only(left: ScreenAdatper.width(10)),
                          child: Text("${_attrValue}"),
                        )
                      ],
                    ),
                    onTap: () {
                      _attrBottomSheet();
                    },
                  ),
                ) : Text(""),
                Divider(),
                Container(
                  height: ScreenAdatper.height(60),
                  child: Row(
                    children: <Widget>[
                      Text("运费", style: TextStyle(fontWeight: FontWeight.bold)),
                      Container(
                          margin: EdgeInsets.only(left: ScreenAdatper.width(10)),
                          child: Text("免运费"),
                        )
                    ],
                  ),
                ),
                Divider(),
              ],
            ),
          )
        ],
      ),
    );
  }
}
